package com.shankungfu.main;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.loopj.android.http.RequestParams;
import com.shankungfu.GlobleConstant;
import com.shankungfu.MainApplication;
import com.shankungfu.R;
import com.shankungfu.adapter.PickItemDetailAdapter;
import com.shankungfu.util.MyAsyncHttpResponseHandler;
import com.shankungfu.util.TestUtils;
import com.shankungfu.util.ToastUtil;
import com.shankungfu.util.WebService;
import com.shankungfu.view.HorizontalListView;

public class PublishCommentActivity extends Activity implements
		OnClickListener, OnItemClickListener {

	public static String photoDir = Environment.getExternalStorageDirectory()
			+ "/ShanKungFu/";
	public static String fileDir = photoDir + "temp_pic/";
	protected final int CAMERA_RESULT = 0x11;
	protected final int PHOTO_ALBUM_RESULT = 0x22;

	private String photoPath;
	private File dirPath;
	private File imagePath;

	private EditText editText;
	private ImageView rigthButton;
	private TextView title;
	private String project_id;
	private HorizontalListView listView;
	private ArrayList<String> picList = new ArrayList<String>();
	private PickItemDetailAdapter adapter;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_comment_layout);

		project_id = getIntent().getStringExtra(CommentActivity.PROJECT_ID);
		editText = (EditText) findViewById(R.id.edittext);
		rigthButton = (ImageView) findViewById(R.id.head_refresh);
		title = (TextView) findViewById(R.id.detail_title);
		listView = (HorizontalListView) findViewById(R.id.pic_listview);

		adapter = new PickItemDetailAdapter(this, MainApplication.getOptions());
		adapter.setData(picList);
		listView.setAdapter(adapter);

		setListViewData();

		title.setText("发表评论");
		rigthButton.setImageResource(R.drawable.send_button);

	}

	private void setListViewData() {
		if (picList != null && picList.size() > 0) {
			listView.setVisibility(View.VISIBLE);
			listView.setOnItemClickListener(this);
		} else {
			listView.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		String sendContent = editText.getText().toString();

		switch (v.getId()) {
		case R.id.head_refresh:

			if (!TextUtils.isEmpty(sendContent)) {
				send(sendContent);
			} else {
				ToastUtil.showMessageText(this, "请说点什么吧！");
			}
			break;
		case R.id.head_goback:
			onBackPressed();
			break;
		case R.id.add_pic:
			String [] pick = new String[] {"拍照", "从手机相册"};
			showListDialog(pick);
			break;
		}

	}
	
	private void showListDialog(final String[] listData) {
		AlertDialog.Builder listDia=new AlertDialog.Builder(this); 
		listDia.setTitle(null);
        listDia.setItems(listData, new DialogInterface.OnClickListener() { 
             
            @Override 
            public void onClick(DialogInterface dialog, int which) { 
            	
            	switch (which) {
				case 0: //拍照
					pictureForCamera();
					break;
				case 1: //相册
					pictureForAlbum();
					break;
				}
            } 
        }); 
        listDia.create().show(); 
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == CAMERA_RESULT && resultCode == RESULT_OK) {

			TestUtils.logI("选择的图片的地址是： " + photoPath);
			picList.add(handlePic(photoPath));
		} else if (requestCode == PHOTO_ALBUM_RESULT && resultCode == RESULT_OK) {
			Bitmap bm = null;
			// 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
			ContentResolver resolver = getContentResolver();
			Uri uri = data.getData();
			// 获得路径
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = managedQuery(uri, proj, null, null, null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			// 最后根据索引值获取图片路径
			String path = cursor.getString(column_index);

			TestUtils.logI("选择的图片的地址是： " + path);
			picList.add(handlePic(path));
		}

		setListViewData();
		adapter.setData(picList);
		adapter.notifyDataSetChanged();
	}

	/**
	 * 调用系统的照相机 wangqing 2013-6-13 void
	 */
	private void pictureForCamera() {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

		try {
			photoPath = photoDir + getPhotoFileName();
			dirPath = new File(photoDir);
			imagePath = new File(photoPath);
			if (!dirPath.exists()) {
				dirPath.mkdir();
			}
			if (!imagePath.exists()) {
				imagePath.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imagePath));
		startActivityForResult(intent, CAMERA_RESULT);
	}

	/**
	 * 从相册选择照片 wangqing 2013-6-13 void
	 */
	private void pictureForAlbum() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		// intent.putExtra("crop", "true");
		// //从相册选择图片，并对图片剪辑,下面是对图片的剪切处理
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);

		startActivityForResult(intent, PHOTO_ALBUM_RESULT);
	}

	/** 获取照片的名字 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}

	private void send(String content) {
		
		dialog = new ProgressDialog(this);
		dialog.show(this, null, "正在发布中...");
		
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();

		params.add("serviceId", "add_comment");
		params.add("project_Id", project_id);
		params.add("comment_content", content);

		if (picList != null && picList.size() > 0) {
			for (int i = 0; i < picList.size(); i++) {
				String picPath = picList.get(i);
				File newFile = new File(URI.create(picPath));
//				File newFile = new File(picPath);
				try {
					params.put(newFile.getName(), newFile);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}

		// File file1 = new File(fileDir + "/a.jpg");
		// File file2 = new File(fileDir + "/b.jpg");
		// try {
		// params.put(file1.getName(), file1);
		// params.put(file2.getName(), file2);
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// }

		MyAsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {
					ToastUtil.showMessageText(PublishCommentActivity.this,
							"发布成功");
					dialog.dismiss();
					setResult(CommentActivity.SUCCESS_CODE);
					finish();
				} else {
					dialog.dismiss();
					ToastUtil.showMessageText(PublishCommentActivity.this,
							"发布失败");
				}
			}

			@Override
			public void onFailure(String content) {
				ToastUtil.showMessageText(PublishCommentActivity.this, "发布失败");
			}
		};
		responseHandler.setShowNotNetToast(false);
		httpclient.request(GlobleConstant.ADD_REPLY, params, responseHandler);
	}

	private String handlePic(String picPath) {
		File file = new File(picPath);

		try {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = false;
			options.inSampleSize = 6;// 宽度和高度设置为原来的1/6
			FileInputStream fileInputStream = new FileInputStream(picPath);
			Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream, null,
					options);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

			byte[] b = baos.toByteArray();

			// 对图片的二次处理
			double size = b.length / 1024; // KB
			if (size > 100) { // 进行压缩
				ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
				double j = size / 400;
				Bitmap bmp = zooImage(bitmap, bitmap.getWidth() / Math.sqrt(j),
						bitmap.getHeight() / Math.sqrt(j));
				bmp.compress(Bitmap.CompressFormat.JPEG, 100, baoStream);
				b = baos.toByteArray();
			}
			writeDataToFile(b, fileDir + file.getName());

			return  "file://" + fileDir + file.getName();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		return "";
	}

	/**
	 * 将处理过的图片保存到本地的 /ChinaJoyPicture/MyPhotograph/ 目录下面 wangqing 2013-7-12 void
	 * 
	 * @param b
	 * @param fileName
	 */
	private void writeDataToFile(byte[] b, String fileName) {
		try {
			File dir = new File(fileDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(fileName);
			fos.write(b);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	private void startImagePagerActivity(int position, String[] imageUrls) {
		Intent intent = new Intent(this, ImagePagerActivity.class);
		intent.putExtra(com.shankungfu.GlobleConstant.Extra.IMAGES, imageUrls);
		intent.putExtra(com.shankungfu.GlobleConstant.Extra.IMAGE_POSITION,
				position);
		startActivity(intent);
	}

	/**
	 * 压缩图片 WangQing 2013-6-27
	 */
	private Bitmap zooImage(Bitmap bitmap, double newWidth, double newHeight) {

		// 获取这个图片的宽和高
		float width = bitmap.getWidth();
		float height = bitmap.getHeight();
		// 创建图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, (int) width,
				(int) height, matrix, true);
		return bmp;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		startImagePagerActivity(position, picList.toArray(new String[] {}));
	}

}
